package com.example.mygrade.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.example.mygrade.domain.Course;
import com.example.mygrade.domain.Student;
import com.example.mygrade.repository.CourseRepository;
import com.example.mygrade.service.CourseService;
import com.example.mygrade.vo.Import;
import com.example.mygrade.vo.importCourse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class CourseImplService implements CourseService {
    @Autowired
    private CourseRepository courseRepository;

    public List<Course> findAll(){
        return courseRepository.findAll();
    }
    /**
     * 只做分页的查询
     * @param pageable
     * @return
     */
    public Page<Course> findAll(Pageable pageable){
        return courseRepository.findAll(pageable);
    }

    public Page<Course> findAll(Example<Course> student, Pageable pageable){
        return courseRepository.findAll(student,pageable);
    }

    /**
     * 按id进行查询
     * @param id 主键，整数
     * @return
     */
    public Course findById(Integer id){

        Course course =courseRepository.findById(id).orElse(null);
        return course;
    }

    public Course insert(Course course){
        return courseRepository.save(course);
    }

    public Course update(Course course){

        return courseRepository.save(course);
    }

    public void delete(Integer id){
        Course course = new Course();
        course.setId(id);
        courseRepository.delete(course);
    }
    public void delete(Integer[] arr){
        Course course = new Course();
        for (int i = 0;i < arr.length;i++){
            course.setId(arr[i]);
            courseRepository.delete(course);
        }
    }


    @Override
    public int insertCourse(MultipartFile file) throws Exception {
        int result = 0;
        //存放excel表中所有数据
        List<Course> eaxmList = new ArrayList<>();

        //file.getOriginalFilename()方法 得到上传时的文件名
        String fileName = file.getOriginalFilename();
        //截取文件名的后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);

        //file.getInputStream()方法  返回InputStream对象 读取文件的内容
        InputStream ins = file.getInputStream();
        Workbook wb = null;
        /*判断文件后缀
            XSSF － 提供读写Microsoft Excel OOXML XLSX格式档案的功能。
            HSSF － 提供读写Microsoft Excel XLS格式档案的功能。*/
        if(suffix.equals("xlsx")){
            wb = new XSSFWorkbook(ins);
        }else{
            wb = new HSSFWorkbook(ins);
        }

        //获取excel表单的sheet对象
        Sheet sheet = wb.getSheetAt(0);
        //如果sheet不为空，就开始遍历表中的数据
        if(null != sheet){
            //line = 1 :从表的第2行开始获取记录
            for(int line = 1; line <= sheet.getLastRowNum();line++){

                //excel表单的sheet的行对象
                Row row = sheet.getRow(line);

                //如果某行为空，跳出本行
                if(null == row){
                    continue;
                }
                //获取第一个单元格的内容
                //表示获取单元格中的内容是String字符串类型
                row.getCell(0).setCellType(CellType.STRING);
                row.getCell(1).setCellType(CellType.STRING);

                String cno = row.getCell(0).getStringCellValue();
                String cname = row.getCell(1).getStringCellValue();


                //这解决的是单元格内读取的日期是天（写的是年月日，但是读取后变成了总天数），需要休眠操作在转换成年月日格式
//                Calendar calendar = new GregorianCalendar(1900,0,-1);
//                Date d = calendar.getTime();
//                Date examtime = DateUtils.addDays(d,Integer.valueOf(examti);
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                String timeFormat = sdf.format(examtime);


                //获取第二个单元格的内容
                //格式是number
//                Integer sage = Integer.valueOf(row.getCell(3).getStringCellValue());
//
//                Integer classid = Integer.valueOf(row.getCell(4).getStringCellValue());
//                Integer gradeid = Integer.valueOf(row.getCell(5).getStringCellValue());

                Double chour1 = row.getCell(2).getNumericCellValue();
                int chour = new Double(chour1).intValue();

                Double credit1 = row.getCell(3).getNumericCellValue();
                int credit = new Double(credit1).intValue();

                Double deptid1 = row.getCell(4).getNumericCellValue();
                int deptid = new Double(deptid1).intValue();

                row.getCell(5).setCellType(CellType.STRING);
                String mid = row.getCell(5).getStringCellValue();

                Double xkrs1 = row.getCell(6).getNumericCellValue();
                int xkrs = new Double(xkrs1).intValue();

                Course eaxm = new Course();

                eaxm.setCno(cno);
                eaxm.setCname(cname);
                eaxm.setChour(chour);
                eaxm.setCredit(credit);
                eaxm.setDeptid(deptid);
                eaxm.setMid(mid);
                eaxm.setXkrs(xkrs);


                eaxmList.add(eaxm);

            }
//            //这其实可以在做一下 判断  是否数据库里已经存在了你要导入数据，我么得写，不想写，懒，难受
            for(Course eaxm:eaxmList){

//                List<Student> students = studentRepository.findBySnameLike(eaxm.getSname());
//                if (students.size() == 0){
//                    result = studentMapper.addExcelStudent(eaxm);
                Course course = new Course();
                course.setCno(eaxm.getCno());
                course.setCname(eaxm.getCname());
                course.setChour(eaxm.getChour());
                course.setCredit(eaxm.getCredit());
                course.setDeptid(eaxm.getDeptid());
                course.setMid(eaxm.getMid());
                course.setXkrs(eaxm.getXkrs());
                courseRepository.save(course);
                if(course != null){
                    result = 1;
                }
//                    System.out.println(result);
//                }

            }
        }
        return result;
    }

    /**
     * excel导出课程表
     * @param response
     */
    public void exportCourse(HttpServletResponse response){
        try {
            //从数据库查询到数据
            List<Course> courses = courseRepository.findAll();

            //设置信息头，告诉浏览器内容为excel类型
            response.setHeader("content-Type", "application/vnd.ms-excel");
            //设置下载名称
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("课程信息表.xls", StandardCharsets.UTF_8.name()));
            //字节流输出
            ServletOutputStream out = response.getOutputStream();
            //设置excel参数
            ExportParams params = new ExportParams();
            //设置sheet名
            params.setSheetName("课程列表");
            //设置标题
            params.setTitle("课程信息表");

            //转成对应的类型;要不然会报错，虽然也可以导出成功。
            List<importCourse> exportUsers = changeType(courses);
            //导入excel
            Workbook workbook = ExcelExportUtil.exportExcel(params, importCourse.class,exportUsers );
            //写入
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 转成导出vo
     *
     * @param users  users集合
     */
    private List<importCourse> changeType(List<Course> users) {
        List<importCourse> res = new ArrayList<>();
        for (Course user : users) {
            importCourse exportUser = new importCourse(user);
            res.add(exportUser);
        }
        return res;
    }
}
